#!/bin/bash

# Staging环境完整配置脚本
# 创建与Production架构一致的独立测试环境
# 使用方法: chmod +x staging-complete-setup.sh && ./staging-complete-setup.sh

echo "🚀 开始创建Staging环境..."
echo "时间: $(date)"
echo "========================================"

# 配置变量
SERVER_IP="47.237.10.129"
SERVER_USER="root"
STAGING_PORT="3001"
STAGING_API_DOMAIN="staging-api.cumrbull.com.sg"
STAGING_ADMIN_DOMAIN="staging-admin.cumrbull.com.sg"

# 数据库配置
DB_HOST="rm-t4n2um727ltmubz.mysql.singapore.rds.aliyuncs.com"
DB_PORT="3306"
STAGING_DB_NAME="cumrbull_staging"
STAGING_DB_USER="cmb_staging"
STAGING_DB_PASS="Staging123!@#"
STAGING_DB_READONLY_USER="cmb_staging_readonly"
STAGING_DB_READONLY_PASS="ReadOnly123!"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

# 1. 创建Staging环境变量文件
create_staging_env() {
    log_step "创建Staging环境变量文件..."
    
    # 生成随机密钥
    JWT_SECRET="staging_jwt_$(openssl rand -hex 32)"
    JWT_REFRESH_SECRET="staging_refresh_$(openssl rand -hex 32)"
    ENCRYPTION_KEY="staging_enc_$(openssl rand -hex 16)"
    
    cat > backend/.env.staging << EOF
# Staging环境配置文件
# 创建时间: $(date)
# 用途: 独立测试环境，与生产环境架构一致

# 环境标识
NODE_ENV=staging
APP_ENV=staging
PORT=$STAGING_PORT

# 数据库配置 - 独立的Staging数据库
DB_HOST=$DB_HOST
DB_PORT=$DB_PORT
DB_USER=$STAGING_DB_USER
DB_PASSWORD=$STAGING_DB_PASS
DB_NAME=$STAGING_DB_NAME
DATABASE_URL=mysql://$STAGING_DB_USER:$(echo $STAGING_DB_PASS | sed 's/!/\%21/g' | sed 's/@/\%40/g' | sed 's/#/\%23/g' | sed 's/\$/\%24/g')@$DB_HOST:$DB_PORT/$STAGING_DB_NAME

# JWT配置 - 独立的密钥
JWT_SECRET=$JWT_SECRET
JWT_REFRESH_SECRET=$JWT_REFRESH_SECRET
JWT_EXPIRES_IN=24h
JWT_REFRESH_EXPIRES_IN=7d

# 域名配置 - Staging专用域名
API_BASE_URL=https://$STAGING_API_DOMAIN
FRONTEND_URL=https://staging.cumrbull.com.sg
ADMIN_URL=https://$STAGING_ADMIN_DOMAIN

# CORS配置 - 允许本地开发和Staging域名
CORS_ORIGIN=https://$STAGING_ADMIN_DOMAIN,https://staging.cumrbull.com.sg,http://localhost:3001,http://localhost:3002,http://localhost:5173

# 安全配置
ENCRYPTION_KEY=$ENCRYPTION_KEY
BCRYPT_SALT_ROUNDS=10
RATE_LIMIT_WINDOW_MS=900000
RATE_LIMIT_MAX_REQUESTS=200

# 文件上传配置
UPLOAD_PATH=./uploads/staging
MAX_FILE_SIZE=10485760
ALLOWED_FILE_TYPES=jpg,jpeg,png,gif,pdf,doc,docx

# 邮件配置 - 测试环境
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_USER=staging@cumrbull.com.sg
EMAIL_PASS=staging-app-password
EMAIL_FROM=staging-noreply@cumrbull.com.sg
EMAIL_TEMPLATE_PATH=./templates/emails

# Redis配置
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=
REDIS_DB=1

# 日志配置
LOG_LEVEL=debug
LOG_FILE=./logs/staging.log
LOG_MAX_SIZE=10m
LOG_MAX_FILES=5

# 调试配置
DEBUG=app:*
VERBOSE_LOGGING=true
API_DOCS_ENABLED=true

# 测试配置
TEST_MODE=false
MOCK_EXTERNAL_APIS=false
SEED_DATABASE=false

# 监控配置
HEALTH_CHECK_ENABLED=true
METRICS_ENABLED=true
PERFORMANCE_MONITORING=true

# 缓存配置
CACHE_TTL=300
CACHE_ENABLED=true

# 第三方服务配置 (测试环境)
PAYMENT_GATEWAY_URL=https://sandbox.payment.com
SMS_PROVIDER_URL=https://api.test-sms.com
EOF

    log_info "✅ Staging环境变量文件已创建: backend/.env.staging"
}

# 2. 创建Staging数据库初始化脚本
create_database_scripts() {
    log_step "创建数据库初始化脚本..."
    
    # 创建scripts目录
    mkdir -p scripts/staging
    
    # 数据库创建脚本
    cat > scripts/staging/create-staging-database.sql << EOF
-- Staging环境数据库初始化脚本
-- 创建时间: $(date)
-- 用途: 创建独立的Staging数据库和用户

-- 创建Staging数据库
CREATE DATABASE IF NOT EXISTS \`$STAGING_DB_NAME\` 
CHARACTER SET utf8mb4 
COLLATE utf8mb4_unicode_ci;

-- 创建Staging用户（完全权限）
CREATE USER IF NOT EXISTS '$STAGING_DB_USER'@'%' IDENTIFIED BY '$STAGING_DB_PASS';
GRANT ALL PRIVILEGES ON \`$STAGING_DB_NAME\`.* TO '$STAGING_DB_USER'@'%';

-- 创建只读用户
CREATE USER IF NOT EXISTS '$STAGING_DB_READONLY_USER'@'%' IDENTIFIED BY '$STAGING_DB_READONLY_PASS';
GRANT SELECT ON \`$STAGING_DB_NAME\`.* TO '$STAGING_DB_READONLY_USER'@'%';

-- 刷新权限
FLUSH PRIVILEGES;

-- 显示创建结果
SELECT 'Staging数据库创建完成' as status;
SHOW DATABASES LIKE '$STAGING_DB_NAME';
SELECT User, Host FROM mysql.user WHERE User IN ('$STAGING_DB_USER', '$STAGING_DB_READONLY_USER');
EOF

    # 数据库连接测试脚本
    cat > scripts/staging/test-staging-database.js << EOF
#!/usr/bin/env node

// Staging数据库连接测试脚本
// 使用方法: node scripts/staging/test-staging-database.js

const mysql = require('mysql2/promise');
require('dotenv').config({ path: './backend/.env.staging' });

const config = {
  host: process.env.DB_HOST,
  port: parseInt(process.env.DB_PORT),
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  connectTimeout: 10000,
  acquireTimeout: 10000,
  timeout: 10000
};

const readOnlyConfig = {
  host: process.env.DB_HOST,
  port: parseInt(process.env.DB_PORT),
  user: '$STAGING_DB_READONLY_USER',
  password: '$STAGING_DB_READONLY_PASS',
  database: process.env.DB_NAME,
  connectTimeout: 10000
};

async function testConnection(config, userType) {
  try {
    console.log(\`\\n🔍 测试\${userType}连接...\`);
    console.log(\`Host: \${config.host}:\${config.port}\`);
    console.log(\`Database: \${config.database}\`);
    console.log(\`User: \${config.user}\`);
    
    const connection = await mysql.createConnection(config);
    
    // 基本连接测试
    const [versionResult] = await connection.execute('SELECT VERSION() as version, NOW() as current_time, DATABASE() as current_db');
    console.log(\`✅ \${userType}连接成功\`);
    console.log(\`   数据库版本: \${versionResult[0].version}\`);
    console.log(\`   当前数据库: \${versionResult[0].current_db}\`);
    console.log(\`   服务器时间: \${versionResult[0].current_time}\`);
    
    // 权限测试
    try {
      const [tables] = await connection.execute(\`
        SELECT COUNT(*) as table_count 
        FROM information_schema.tables 
        WHERE table_schema = ?\`, [config.database]);
      console.log(\`   数据库表数量: \${tables[0].table_count}\`);
    } catch (error) {
      console.log(\`   ⚠️ 无法查询表信息: \${error.message}\`);
    }
    
    // 写权限测试（仅对完全权限用户）
    if (userType === '完全权限用户') {
      try {
        await connection.execute(\`
          CREATE TABLE IF NOT EXISTS staging_test (
            id INT AUTO_INCREMENT PRIMARY KEY,
            test_data VARCHAR(255),
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
          )\`);
        
        await connection.execute(\`
          INSERT INTO staging_test (test_data) VALUES (?)\`, 
          [\`测试数据 - \${new Date().toISOString()}\`]);
        
        const [testResult] = await connection.execute('SELECT COUNT(*) as count FROM staging_test');
        console.log(\`   ✅ 写权限测试通过，测试表记录数: \${testResult[0].count}\`);
        
        // 清理测试数据
        await connection.execute('DROP TABLE IF EXISTS staging_test');
        console.log(\`   🧹 测试表已清理\`);
      } catch (error) {
        console.log(\`   ❌ 写权限测试失败: \${error.message}\`);
      }
    }
    
    await connection.end();
    return true;
  } catch (error) {
    console.log(\`❌ \${userType}连接失败: \${error.message}\`);
    console.log(\`   错误代码: \${error.code}\`);
    if (error.code === 'ECONNREFUSED') {
      console.log(\`   💡 建议: 检查数据库服务器是否运行，端口是否开放\`);
    } else if (error.code === 'ER_ACCESS_DENIED_ERROR') {
      console.log(\`   💡 建议: 检查用户名和密码是否正确\`);
    } else if (error.code === 'ENOTFOUND') {
      console.log(\`   💡 建议: 检查数据库主机地址是否正确\`);
    }
    return false;
  }
}

async function main() {
  console.log('🗄️ Staging数据库连接测试');
  console.log('=' .repeat(50));
  
  const results = [];
  
  // 测试完全权限用户连接
  results.push(await testConnection(config, '完全权限用户'));
  
  // 测试只读用户连接
  results.push(await testConnection(readOnlyConfig, '只读用户'));
  
  console.log('\\n📊 测试总结');
  console.log('=' .repeat(50));
  const successCount = results.filter(r => r).length;
  const totalCount = results.length;
  console.log(\`成功: \${successCount}/\${totalCount}\`);
  
  if (successCount === totalCount) {
    console.log('🎉 所有数据库连接测试通过！');
    process.exit(0);
  } else {
    console.log('❌ 部分数据库连接测试失败，请检查配置');
    process.exit(1);
  }
}

// 处理未捕获的异常
process.on('unhandledRejection', (error) => {
  console.error('❌ 未处理的异常:', error.message);
  process.exit(1);
});

main();
EOF

    # 数据迁移脚本
    cat > scripts/staging/migrate-to-staging.js << EOF
#!/usr/bin/env node

// 生产数据迁移到Staging环境脚本
// 使用方法: node scripts/staging/migrate-to-staging.js

const mysql = require('mysql2/promise');
require('dotenv').config();

// 生产环境配置
const prodConfig = {
  host: process.env.DB_HOST,
  port: parseInt(process.env.DB_PORT),
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME
};

// Staging环境配置
const stagingConfig = {
  host: process.env.DB_HOST,
  port: parseInt(process.env.DB_PORT),
  user: '$STAGING_DB_USER',
  password: '$STAGING_DB_PASS',
  database: '$STAGING_DB_NAME'
};

async function migrateData() {
  let prodConnection, stagingConnection;
  
  try {
    console.log('🔄 开始数据迁移...');
    
    // 连接到生产和Staging数据库
    prodConnection = await mysql.createConnection(prodConfig);
    stagingConnection = await mysql.createConnection(stagingConfig);
    
    console.log('✅ 数据库连接成功');
    
    // 获取生产环境的表结构
    const [tables] = await prodConnection.execute(\`
      SELECT table_name 
      FROM information_schema.tables 
      WHERE table_schema = ? AND table_type = 'BASE TABLE'\`, 
      [prodConfig.database]);
    
    console.log(\`📋 发现 \${tables.length} 个表需要迁移\`);
    
    for (const table of tables) {
      const tableName = table.table_name;
      console.log(\`\\n🔄 迁移表: \${tableName}\`);
      
      // 获取表结构
      const [createTableResult] = await prodConnection.execute(\`SHOW CREATE TABLE \${tableName}\`);
      const createTableSQL = createTableResult[0]['Create Table'];
      
      // 在Staging环境中创建表
      await stagingConnection.execute(\`DROP TABLE IF EXISTS \${tableName}\`);
      await stagingConnection.execute(createTableSQL);
      
      // 复制数据（限制数量以避免过大的数据集）
      const [data] = await prodConnection.execute(\`SELECT * FROM \${tableName} LIMIT 1000\`);
      
      if (data.length > 0) {
        // 构建插入语句
        const columns = Object.keys(data[0]);
        const placeholders = columns.map(() => '?').join(', ');
        const insertSQL = \`INSERT INTO \${tableName} (\${columns.join(', ')}) VALUES (\${placeholders})\`;
        
        // 批量插入数据
        for (const row of data) {
          const values = columns.map(col => row[col]);
          await stagingConnection.execute(insertSQL, values);
        }
        
        console.log(\`   ✅ 已迁移 \${data.length} 条记录\`);
      } else {
        console.log(\`   ℹ️ 表为空，跳过数据迁移\`);
      }
    }
    
    console.log('\\n🎉 数据迁移完成！');
    
  } catch (error) {
    console.error('❌ 数据迁移失败:', error.message);
    throw error;
  } finally {
    if (prodConnection) await prodConnection.end();
    if (stagingConnection) await stagingConnection.end();
  }
}

if (require.main === module) {
  migrateData().catch(error => {
    console.error('迁移过程中发生错误:', error);
    process.exit(1);
  });
}

module.exports = { migrateData };
EOF

    log_info "✅ 数据库脚本已创建"
}

# 3. 创建Staging Nginx配置
create_staging_nginx_config() {
    log_step "创建Staging Nginx配置..."
    
    cat > nginx-staging.conf << EOF
# Staging环境Nginx配置
# 部署位置: /etc/nginx/conf.d/staging.conf
# 创建时间: $(date)

# 上游服务器配置 - Staging API
upstream staging_api {
    server 127.0.0.1:$STAGING_PORT max_fails=3 fail_timeout=30s;
    keepalive 32;
}

# 限流设置 - Staging环境更宽松
limit_req_zone \$binary_remote_addr zone=staging_api:10m rate=20r/s;
limit_req_zone \$binary_remote_addr zone=staging_login:10m rate=5r/s;

# HTTP重定向 - Staging API域名
server {
    listen 80;
    server_name $STAGING_API_DOMAIN;
    
    # Let's Encrypt验证
    location /.well-known/acme-challenge/ {
        root /var/www/html;
    }
    
    # 重定向到HTTPS
    location / {
        return 301 https://\$host\$request_uri;
    }
}

# HTTP重定向 - Staging管理后台域名
server {
    listen 80;
    server_name $STAGING_ADMIN_DOMAIN;
    
    # Let's Encrypt验证
    location /.well-known/acme-challenge/ {
        root /var/www/html;
    }
    
    # 重定向到HTTPS
    location / {
        return 301 https://\$host\$request_uri;
    }
}

# HTTPS服务器 - Staging API服务
server {
    listen 443 ssl http2;
    server_name $STAGING_API_DOMAIN;
    
    # SSL配置 - 使用独立的Staging证书
    ssl_certificate /etc/letsencrypt/live/$STAGING_API_DOMAIN/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/$STAGING_API_DOMAIN/privkey.pem;
    ssl_session_timeout 1d;
    ssl_session_cache shared:STAGING_SSL:50m;
    ssl_session_tickets off;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    
    # HSTS (较短期限，适合测试)
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    
    # 安全头
    add_header X-Frame-Options DENY always;
    add_header X-Content-Type-Options nosniff always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    
    # 日志
    access_log /var/log/nginx/staging-api.access.log;
    error_log /var/log/nginx/staging-api.error.log;
    
    # 健康检查 - 无限流
    location /health {
        proxy_pass http://staging_api/health;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_connect_timeout 5s;
        proxy_send_timeout 10s;
        proxy_read_timeout 10s;
        
        # 添加Staging标识
        add_header X-Environment "staging" always;
    }
    
    # API文档 - Staging环境启用
    location /docs {
        proxy_pass http://staging_api/docs;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        
        add_header X-Environment "staging" always;
    }
    
    # 登录接口 - 宽松限流
    location ~ ^/api/(auth/login|auth/register) {
        limit_req zone=staging_login burst=10 nodelay;
        
        proxy_pass http://staging_api;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_connect_timeout 10s;
        proxy_send_timeout 30s;
        proxy_read_timeout 30s;
        
        add_header X-Environment "staging" always;
    }
    
    # 一般API接口 - 宽松限流
    location /api/ {
        limit_req zone=staging_api burst=20 nodelay;
        
        proxy_pass http://staging_api;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_connect_timeout 10s;
        proxy_send_timeout 30s;
        proxy_read_timeout 30s;
        
        # 启用详细错误信息（仅Staging）
        proxy_intercept_errors off;
        add_header X-Environment "staging" always;
    }
    
    # 根路径 - API信息
    location / {
        proxy_pass http://staging_api;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        
        add_header X-Environment "staging" always;
    }
    
    # 静态文件服务 - Staging上传文件
    location /uploads/ {
        alias /opt/cumbull/backend/uploads/staging/;
        expires 1h;  # 较短缓存时间
        add_header Cache-Control "public";
        add_header X-Content-Type-Options nosniff;
        add_header X-Environment "staging" always;
    }
}

# HTTPS服务器 - Staging管理后台
server {
    listen 443 ssl http2;
    server_name $STAGING_ADMIN_DOMAIN;
    
    # SSL配置（与API相同）
    ssl_certificate /etc/letsencrypt/live/$STAGING_API_DOMAIN/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/$STAGING_API_DOMAIN/privkey.pem;
    ssl_session_timeout 1d;
    ssl_session_cache shared:STAGING_SSL:50m;
    ssl_session_tickets off;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    
    # 安全头
    add_header X-Frame-Options SAMEORIGIN always;
    add_header X-Content-Type-Options nosniff always;
    add_header X-XSS-Protection "1; mode=block" always;
    
    # 日志
    access_log /var/log/nginx/staging-admin.access.log;
    error_log /var/log/nginx/staging-admin.error.log;
    
    # 管理后台API路由
    location /api/ {
        proxy_pass http://staging_api/api/;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_connect_timeout 30s;
        proxy_send_timeout 30s;
        proxy_read_timeout 30s;
        
        # 启用详细错误信息
        proxy_intercept_errors off;
        add_header X-Environment "staging" always;
    }
    
    # 静态文件服务（管理界面）
    location / {
        root /var/www/staging-admin;
        index index.html;
        try_files \$uri \$uri/ /index.html;
        
        # 如果没有静态文件，显示Staging环境信息
        error_page 404 = @staging_fallback;
        
        add_header X-Environment "staging" always;
    }
    
    location @staging_fallback {
        add_header Content-Type text/html;
        return 200 '
<!DOCTYPE html>
<html>
<head>
    <title>Staging Environment</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 40px; background: #f5f5f5; }
        .container { background: white; padding: 30px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .header { color: #ff6b35; border-bottom: 2px solid #ff6b35; padding-bottom: 10px; }
        .status { background: #fff3cd; border: 1px solid #ffeaa7; padding: 15px; border-radius: 4px; margin: 20px 0; }
        .links a { display: inline-block; margin: 10px 15px 10px 0; padding: 8px 16px; background: #007bff; color: white; text-decoration: none; border-radius: 4px; }
        .links a:hover { background: #0056b3; }
    </style>
</head>
<body>
    <div class="container">
        <h1 class="header">🧪 Staging Environment</h1>
        <div class="status">
            <strong>环境状态:</strong> Staging测试环境<br>
            <strong>域名:</strong> $STAGING_ADMIN_DOMAIN<br>
            <strong>API地址:</strong> $STAGING_API_DOMAIN<br>
            <strong>更新时间:</strong> $(date)
        </div>
        <h3>快速链接:</h3>
        <div class="links">
            <a href="/api/health">健康检查</a>
            <a href="/docs">API文档</a>
            <a href="https://$STAGING_API_DOMAIN">API服务</a>
        </div>
        <p><em>这是Staging测试环境，用于开发和测试。请勿在此环境进行生产操作。</em></p>
    </div>
</body>
</html>';
    }
}
EOF

    log_info "✅ Staging Nginx配置已创建: nginx-staging.conf"
}

# 4. 创建Staging部署脚本
create_staging_deploy_script() {
    log_step "创建Staging部署脚本..."
    
    cat > deploy-staging.sh << 'EOF'
#!/bin/bash

# Staging环境部署脚本
# 将Staging配置部署到服务器

SERVER_IP="47.237.10.129"
SERVER_USER="root"
STAGING_PORT="3001"

echo "🚀 部署Staging环境到服务器..."
echo "服务器: $SERVER_IP"
echo "========================================"

# 1. 上传配置文件
echo "📤 上传配置文件..."
scp backend/.env.staging $SERVER_USER@$SERVER_IP:/opt/cumbull/backend/
scp nginx-staging.conf $SERVER_USER@$SERVER_IP:/etc/nginx/conf.d/staging.conf
scp scripts/staging/*.* $SERVER_USER@$SERVER_IP:/opt/cumbull/scripts/staging/

# 2. 在服务器上执行部署
echo "🔧 在服务器上执行部署..."
ssh $SERVER_USER@$SERVER_IP << 'REMOTE_EOF'
echo "🔧 开始服务器端部署..."

# 进入项目目录
cd /opt/cumbull/backend

# 创建必要目录
mkdir -p logs uploads/staging scripts/staging

# 停止现有Staging进程
echo "停止现有Staging服务..."
pm2 delete cumrbull-staging 2>/dev/null || echo "没有运行的Staging进程"
sleep 2

# 安装依赖（如果需要）
if [ ! -d "node_modules" ]; then
    echo "安装Node.js依赖..."
    npm install --production
fi

# 启动Staging服务
echo "启动Staging服务..."
if [ -f "production-server.js" ]; then
    NODE_ENV=staging pm2 start production-server.js --name "cumrbull-staging" --env staging
elif [ -f "start-server.js" ]; then
    NODE_ENV=staging pm2 start start-server.js --name "cumrbull-staging" --env staging
else
    echo "❌ 找不到启动文件"
    exit 1
fi

# 保存PM2配置
pm2 save

echo "等待服务启动..."
sleep 5

# 测试Nginx配置
echo "测试Nginx配置..."
nginx -t
if [ $? -eq 0 ]; then
    echo "✅ Nginx配置语法正确"
    systemctl reload nginx
    echo "✅ Nginx已重新加载"
else
    echo "❌ Nginx配置语法错误"
    exit 1
fi

# 检查服务状态
echo "\n📊 检查服务状态..."
echo "PM2进程状态:"
pm2 status

echo "\n端口监听状态:"
netstat -tlnp | grep -E ':(80|443|3000|3001)'

echo "\n测试Staging健康检查:"
curl -s http://localhost:3001/health || echo "Staging健康检查失败"

echo "\n✅ Staging环境部署完成"
REMOTE_EOF

# 3. 验证部署结果
echo "\n🧪 验证部署结果..."
echo "测试Staging API健康检查:"
if curl -s -m 10 https://staging-api.cumrbull.com.sg/health; then
    echo "✅ Staging API健康检查正常"
else
    echo "⚠️ Staging API健康检查失败（可能需要配置DNS和SSL）"
fi

echo "\n🎉 Staging环境部署完成！"
echo "========================================"
echo "📋 后续步骤:"
echo "1. 配置DNS解析: staging-api.cumrbull.com.sg -> $SERVER_IP"
echo "2. 配置DNS解析: staging-admin.cumrbull.com.sg -> $SERVER_IP"
echo "3. 申请SSL证书: certbot certonly --nginx -d staging-api.cumrbull.com.sg -d staging-admin.cumrbull.com.sg"
echo "4. 创建Staging数据库: mysql < scripts/staging/create-staging-database.sql"
echo "5. 测试数据库连接: node scripts/staging/test-staging-database.js"
echo "6. 运行数据迁移: node scripts/staging/migrate-to-staging.js"
echo "7. 验证Staging环境: ./connectivity-test.sh"
EOF

    chmod +x deploy-staging.sh
    log_info "✅ Staging部署脚本已创建: deploy-staging.sh"
}

# 5. 创建Staging环境管理脚本
create_staging_management_scripts() {
    log_step "创建Staging环境管理脚本..."
    
    # 创建管理脚本目录
    mkdir -p scripts/staging/management
    
    # Staging服务控制脚本
    cat > scripts/staging/management/staging-control.sh << 'EOF'
#!/bin/bash

# Staging环境服务控制脚本
# 使用方法: ./staging-control.sh [start|stop|restart|status|logs]

SERVER_IP="47.237.10.129"
SERVER_USER="root"

case "$1" in
    start)
        echo "🚀 启动Staging服务..."
        ssh $SERVER_USER@$SERVER_IP "cd /opt/cumbull/backend && pm2 start cumrbull-staging"
        ;;
    stop)
        echo "🛑 停止Staging服务..."
        ssh $SERVER_USER@$SERVER_IP "pm2 stop cumrbull-staging"
        ;;
    restart)
        echo "🔄 重启Staging服务..."
        ssh $SERVER_USER@$SERVER_IP "pm2 restart cumrbull-staging"
        ;;
    status)
        echo "📊 Staging服务状态:"
        ssh $SERVER_USER@$SERVER_IP "pm2 status cumrbull-staging"
        ;;
    logs)
        echo "📝 Staging服务日志:"
        ssh $SERVER_USER@$SERVER_IP "pm2 logs cumrbull-staging --lines 50"
        ;;
    *)
        echo "使用方法: $0 {start|stop|restart|status|logs}"
        exit 1
        ;;
esac
EOF

    # Staging数据库管理脚本
    cat > scripts/staging/management/staging-db-manager.sh << 'EOF'
#!/bin/bash

# Staging数据库管理脚本
# 使用方法: ./staging-db-manager.sh [create|test|backup|restore|reset]

DB_HOST="rm-t4n2um727ltmubz.mysql.singapore.rds.aliyuncs.com"
DB_PORT="3306"
STAGING_DB_NAME="cumrbull_staging"
STAGING_DB_USER="cmb_staging"
STAGING_DB_PASS="Staging123!@#"

case "$1" in
    create)
        echo "🗄️ 创建Staging数据库..."
        mysql -h $DB_HOST -P $DB_PORT -u cmb_admin -p < ../create-staging-database.sql
        ;;
    test)
        echo "🧪 测试Staging数据库连接..."
        node ../test-staging-database.js
        ;;
    backup)
        echo "💾 备份Staging数据库..."
        BACKUP_FILE="staging_backup_$(date +%Y%m%d_%H%M%S).sql"
        mysqldump -h $DB_HOST -P $DB_PORT -u $STAGING_DB_USER -p$STAGING_DB_PASS $STAGING_DB_NAME > $BACKUP_FILE
        echo "备份已保存到: $BACKUP_FILE"
        ;;
    restore)
        if [ -z "$2" ]; then
            echo "请指定备份文件: $0 restore <backup_file>"
            exit 1
        fi
        echo "🔄 恢复Staging数据库..."
        mysql -h $DB_HOST -P $DB_PORT -u $STAGING_DB_USER -p$STAGING_DB_PASS $STAGING_DB_NAME < $2
        ;;
    reset)
        echo "⚠️ 重置Staging数据库（将删除所有数据）..."
        read -p "确认重置？(y/N): " confirm
        if [ "$confirm" = "y" ] || [ "$confirm" = "Y" ]; then
            mysql -h $DB_HOST -P $DB_PORT -u $STAGING_DB_USER -p$STAGING_DB_PASS -e "DROP DATABASE IF EXISTS $STAGING_DB_NAME; CREATE DATABASE $STAGING_DB_NAME CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
            echo "✅ Staging数据库已重置"
        else
            echo "取消重置操作"
        fi
        ;;
    *)
        echo "使用方法: $0 {create|test|backup|restore|reset}"
        exit 1
        ;;
esac
EOF

    # 设置执行权限
    chmod +x scripts/staging/management/*.sh
    
    log_info "✅ Staging管理脚本已创建"
}

# 6. 创建完整的设置验证脚本
create_staging_verification() {
    log_step "创建Staging环境验证脚本..."
    
    cat > verify-staging-setup.sh << 'EOF'
#!/bin/bash

# Staging环境设置验证脚本
# 验证所有Staging配置是否正确

echo "🔍 验证Staging环境设置..."
echo "========================================"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

PASSED=0
FAILED=0

check_file() {
    if [ -f "$1" ]; then
        echo -e "${GREEN}✅${NC} $1 存在"
        PASSED=$((PASSED + 1))
    else
        echo -e "${RED}❌${NC} $1 不存在"
        FAILED=$((FAILED + 1))
    fi
}

check_directory() {
    if [ -d "$1" ]; then
        echo -e "${GREEN}✅${NC} 目录 $1 存在"
        PASSED=$((PASSED + 1))
    else
        echo -e "${RED}❌${NC} 目录 $1 不存在"
        FAILED=$((FAILED + 1))
    fi
}

echo "\n📁 检查文件和目录..."
check_file "backend/.env.staging"
check_file "nginx-staging.conf"
check_file "deploy-staging.sh"
check_file "scripts/staging/create-staging-database.sql"
check_file "scripts/staging/test-staging-database.js"
check_file "scripts/staging/migrate-to-staging.js"
check_directory "scripts/staging"
check_directory "scripts/staging/management"

echo "\n🔧 检查脚本权限..."
if [ -x "deploy-staging.sh" ]; then
    echo -e "${GREEN}✅${NC} deploy-staging.sh 可执行"
    PASSED=$((PASSED + 1))
else
    echo -e "${RED}❌${NC} deploy-staging.sh 不可执行"
    FAILED=$((FAILED + 1))
fi

echo "\n📋 检查环境变量配置..."
if grep -q "NODE_ENV=staging" backend/.env.staging; then
    echo -e "${GREEN}✅${NC} NODE_ENV 配置正确"
    PASSED=$((PASSED + 1))
else
    echo -e "${RED}❌${NC} NODE_ENV 配置错误"
    FAILED=$((FAILED + 1))
fi

if grep -q "PORT=3001" backend/.env.staging; then
    echo -e "${GREEN}✅${NC} PORT 配置正确"
    PASSED=$((PASSED + 1))
else
    echo -e "${RED}❌${NC} PORT 配置错误"
    FAILED=$((FAILED + 1))
fi

if grep -q "cumrbull_staging" backend/.env.staging; then
    echo -e "${GREEN}✅${NC} 数据库名称配置正确"
    PASSED=$((PASSED + 1))
else
    echo -e "${RED}❌${NC} 数据库名称配置错误"
    FAILED=$((FAILED + 1))
fi

echo "\n🌐 检查Nginx配置..."
if grep -q "staging-api.cumrbull.com.sg" nginx-staging.conf; then
    echo -e "${GREEN}✅${NC} Staging API域名配置正确"
    PASSED=$((PASSED + 1))
else
    echo -e "${RED}❌${NC} Staging API域名配置错误"
    FAILED=$((FAILED + 1))
fi

if grep -q "127.0.0.1:3001" nginx-staging.conf; then
    echo -e "${GREEN}✅${NC} 上游服务器配置正确"
    PASSED=$((PASSED + 1))
else
    echo -e "${RED}❌${NC} 上游服务器配置错误"
    FAILED=$((FAILED + 1))
fi

echo "\n📊 验证总结"
echo "========================================"
echo "通过: $PASSED"
echo "失败: $FAILED"
echo "总计: $((PASSED + FAILED))"

if [ $FAILED -eq 0 ]; then
    echo -e "\n${GREEN}🎉 Staging环境设置验证通过！${NC}"
    echo "\n📋 下一步操作:"
    echo "1. 运行部署脚本: ./deploy-staging.sh"
    echo "2. 配置DNS解析"
    echo "3. 申请SSL证书"
    echo "4. 创建数据库"
    echo "5. 运行连通性测试"
    exit 0
else
    echo -e "\n${RED}❌ Staging环境设置验证失败！${NC}"
    echo "请修复上述问题后重新运行验证。"
    exit 1
fi
EOF

    chmod +x verify-staging-setup.sh
    log_info "✅ Staging验证脚本已创建: verify-staging-setup.sh"
}

# 7. 生成设置总结报告
generate_setup_summary() {
    log_step "生成Staging环境设置总结..."
    
    cat > STAGING_SETUP_SUMMARY.md << EOF
# Staging环境设置总结

**创建时间**: $(date)  
**环境类型**: 独立测试环境  
**架构**: 与Production一致

## 📋 已创建的文件

### 🔧 配置文件
- \`backend/.env.staging\` - Staging环境变量
- \`nginx-staging.conf\` - Staging Nginx配置

### 📜 数据库脚本
- \`scripts/staging/create-staging-database.sql\` - 数据库创建脚本
- \`scripts/staging/test-staging-database.js\` - 数据库连接测试
- \`scripts/staging/migrate-to-staging.js\` - 数据迁移脚本

### 🚀 部署脚本
- \`deploy-staging.sh\` - 主部署脚本
- \`scripts/staging/management/staging-control.sh\` - 服务控制
- \`scripts/staging/management/staging-db-manager.sh\` - 数据库管理

### 🔍 验证脚本
- \`verify-staging-setup.sh\` - 设置验证
- \`connectivity-test.sh\` - 连通性测试（已存在）

## 🌐 Staging环境配置

### 域名配置
- **API域名**: \`$STAGING_API_DOMAIN\`
- **管理后台**: \`$STAGING_ADMIN_DOMAIN\`
- **端口**: $STAGING_PORT

### 数据库配置
- **数据库名**: \`$STAGING_DB_NAME\`
- **用户**: \`$STAGING_DB_USER\` (完全权限)
- **只读用户**: \`$STAGING_DB_READONLY_USER\`
- **主机**: \`$DB_HOST\`

### 安全配置
- 独立的JWT密钥
- 独立的加密密钥
- 宽松的限流设置（适合测试）
- 启用详细错误信息
- 启用API文档

## 🚀 部署步骤

### 1. 验证设置
\`\`\`bash
./verify-staging-setup.sh
\`\`\`

### 2. 部署到服务器
\`\`\`bash
./deploy-staging.sh
\`\`\`

### 3. 配置DNS解析
在DNS提供商处添加A记录：
- \`$STAGING_API_DOMAIN\` → \`$SERVER_IP\`
- \`$STAGING_ADMIN_DOMAIN\` → \`$SERVER_IP\`

### 4. 申请SSL证书
\`\`\`bash
ssh root@$SERVER_IP
certbot certonly --nginx -d $STAGING_API_DOMAIN -d $STAGING_ADMIN_DOMAIN
\`\`\`

### 5. 创建数据库
\`\`\`bash
# 在本地执行
mysql -h $DB_HOST -P $DB_PORT -u cmb_admin -p < scripts/staging/create-staging-database.sql
\`\`\`

### 6. 测试数据库连接
\`\`\`bash
node scripts/staging/test-staging-database.js
\`\`\`

### 7. 迁移测试数据（可选）
\`\`\`bash
node scripts/staging/migrate-to-staging.js
\`\`\`

### 8. 验证部署
\`\`\`bash
./connectivity-test.sh
\`\`\`

## 🔧 日常管理

### 服务控制
\`\`\`bash
# 启动服务
./scripts/staging/management/staging-control.sh start

# 停止服务
./scripts/staging/management/staging-control.sh stop

# 重启服务
./scripts/staging/management/staging-control.sh restart

# 查看状态
./scripts/staging/management/staging-control.sh status

# 查看日志
./scripts/staging/management/staging-control.sh logs
\`\`\`

### 数据库管理
\`\`\`bash
# 测试连接
./scripts/staging/management/staging-db-manager.sh test

# 备份数据
./scripts/staging/management/staging-db-manager.sh backup

# 恢复数据
./scripts/staging/management/staging-db-manager.sh restore backup_file.sql

# 重置数据库
./scripts/staging/management/staging-db-manager.sh reset
\`\`\`

## 🧪 测试流程

### 开发流程
1. **本地开发** (\`npm run dev\`)
2. **Staging联调** (\`https://$STAGING_API_DOMAIN\`)
3. **生产发布** (\`https://api.cumrbull.com.sg\`)

### 测试检查清单
- [ ] API健康检查: \`https://$STAGING_API_DOMAIN/health\`
- [ ] 管理后台: \`https://$STAGING_ADMIN_DOMAIN\`
- [ ] 数据库连接测试
- [ ] 用户认证功能
- [ ] 文件上传功能
- [ ] 邮件发送功能
- [ ] API限流测试
- [ ] 错误处理测试

## 🔍 监控和日志

### 应用日志
- \`/opt/cumbull/backend/logs/staging.log\`
- \`pm2 logs cumrbull-staging\`

### Nginx日志
- \`/var/log/nginx/staging-api.access.log\`
- \`/var/log/nginx/staging-api.error.log\`
- \`/var/log/nginx/staging-admin.access.log\`
- \`/var/log/nginx/staging-admin.error.log\`

### 系统监控
\`\`\`bash
# 服务器资源
htop
df -h
free -h

# 网络连接
netstat -tlnp | grep -E ':(80|443|3000|3001)'

# 进程状态
pm2 status
pm2 monit
\`\`\`

## ⚠️ 注意事项

1. **数据安全**: Staging环境使用独立数据库，避免影响生产数据
2. **访问控制**: 建议限制Staging环境的访问IP
3. **资源监控**: 定期检查服务器资源使用情况
4. **定期备份**: 定期备份Staging数据库
5. **证书更新**: SSL证书自动续期，但需要监控

## 🆘 故障排除

### 常见问题
1. **服务无法启动**: 检查端口占用和环境变量
2. **数据库连接失败**: 检查网络和认证信息
3. **SSL证书问题**: 检查域名解析和证书路径
4. **API返回404**: 检查Nginx配置和上游服务器

### 紧急联系
- 查看实时日志: \`ssh root@$SERVER_IP 'journalctl -f'\`
- 重启所有服务: \`./scripts/staging/management/staging-control.sh restart\`
- 回滚配置: 使用 \`/root/backup/\` 目录中的备份文件

---

**设置状态**: ✅ 配置文件已创建，等待部署  
**下一步**: 运行 \`./verify-staging-setup.sh\` 验证设置
EOF

    log_info "✅ 设置总结已生成: STAGING_SETUP_SUMMARY.md"
}

# 主执行流程
main() {
    echo "🚀 开始创建完整的Staging环境"
    echo "========================================"
    
    create_staging_env
    create_database_scripts
    create_staging_nginx_config
    create_staging_deploy_script
    create_staging_management_scripts
    create_staging_verification
    generate_setup_summary
    
    echo "\n🎉 Staging环境设置完成！"
    echo "========================================"
    echo "📋 已创建的文件:"
    echo "   - backend/.env.staging (环境变量)"
    echo "   - nginx-staging.conf (Nginx配置)"
    echo "   - deploy-staging.sh (部署脚本)"
    echo "   - scripts/staging/ (数据库和管理脚本)"
    echo "   - verify-staging-setup.sh (验证脚本)"
    echo "   - STAGING_SETUP_SUMMARY.md (设置总结)"
    echo ""
    echo "🚀 下一步操作:"
    echo "1. 验证设置: ./verify-staging-setup.sh"
    echo "2. 部署到服务器: ./deploy-staging.sh"
    echo "3. 配置DNS和SSL证书"
    echo "4. 创建数据库和测试连接"
    echo "5. 运行连通性测试: ./connectivity-test.sh"
    echo ""
    echo "📖 详细说明请查看: STAGING_SETUP_SUMMARY.md"
}

# 执行主流程
main "$@"